package com.matrix.draft.rabbitmqspringboot.controller;

import cn.hutool.core.util.StrUtil;
import com.matrix.draft.rabbitmqspringboot.config.RabbitMQConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * 主要前端控制器
 */
@RestController
@RequestMapping("")
public class IndexController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/send/{msg}/{ttl}")
    Object index(@PathVariable("msg") String msg, @PathVariable("ttl") Integer ttl) {
        Message message = MessageBuilder.withBody(msg.getBytes(StandardCharsets.UTF_8)).build();
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.DELAYED_EXCHANGE, // 发到哪个交换机?
                RabbitMQConfig.DELAYED_ROUTING_KEY, // 以什么routingKey?
                message, // 消息对象
                m -> { // 设置一些发布属性
                    m.getMessageProperties().setDelay(ttl);
                    return m;
                }
        );
        return StrUtil.format("{}/{} 发布成功!",msg,ttl);
    }



}
